﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace Archie.Retail.Site.Controllers.Editing
{
    public class DoorManufacturersController : ApiController
    {
        public IEnumerable<Data.DoorManufacturer> GetAll()
        {
            var items = DataManagerLocator.DataManager.GetDoorManufacturers();
            return items;
        }

        public Data.DoorManufacturer LoadOneItem(Guid? id)
        {
            if (id == null)
            {
                return null;
            }

            return DataManagerLocator.DataManager.GetDoorManufacturer(id.Value);
        }

        public HttpResponseMessage Post(Data.DoorManufacturer item)
        {
            if(item == null)
            {
                return new HttpResponseMessage(HttpStatusCode.NotFound);
            }

            DataManagerLocator.DataManager.AddDoorManufacturer(item);
            var response = Request.CreateResponse(HttpStatusCode.Created, item);

            var uri = Url.Link("DefaultApi", new { id = item.Id });
            response.Headers.Location = new Uri(uri);
            return response;
        }

        public void Put(Data.DoorManufacturer item)
        {
            if(item == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            try
            {
                DataManagerLocator.DataManager.UpdateDoorManufacturer(item);
            }
            catch (KeyNotFoundException)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }           
        }

        public HttpResponseMessage Delete(Guid? id)
        {
            if(id == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            try
            {
                DataManagerLocator.DataManager.DeleteDoorManufacturer(id.Value);
            }
            catch (KeyNotFoundException)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            
            return new HttpResponseMessage(HttpStatusCode.NoContent);
        }
    }
}
